﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms; 
using Orid.Management.Statistics.Tools.Decomposition.Logic;
using System.Threading;
using System.Collections;





namespace Orid.Management.Statistics.Tools.Decomposition.UI
{
    public delegate void DecompostiteEnd(Guid orderID );
    public delegate void DecompostiteFinish();
  
    public partial class FormManageDecompositionOrders : FormChildBase
    {
        //ManualResetEvent[] manualEvents = null;

        private int threadCount = 0;

       
        public event EventHandler DecompositionFinished;
        private void onDecompositionFinished(EventArgs e)
        {
            if (DecompositionFinished != null)
            {
                IsAutoRun = false;
                DecompositionFinished(this, e);
            }
        }


        public FormManageDecompositionOrders(FormMain parentForm)
        {
            this.ParentForm = parentForm;

            InitializeComponent();
            this.inputToolStripMenuItem.Click += new EventHandler(inputToolStripMenuItem_Click);
            this.searchToolStripMenuItem.Click += new EventHandler(searchToolStripMenuItem_Click);
            this.deleteToolStripMenuItem.Click += new EventHandler(deleteToolStripMenuItem_Click);

            this.ParentForm.Star += new EventHandler(Star);
            this.ParentForm.Stop += new EventHandler(Stop);
            this.ParentForm.AutoRun += new EventHandler(AutoRun);
            
            this.DecompositionFinished += new EventHandler(FormManageDecompositionOrders_DecompositionFinished);

     

          

        }

 

 


        void FormManageDecompositionOrders_DecompositionFinished(object sender, EventArgs e)
        {
            ParentForm.IsRun = true;
        }

        void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ListView.SelectedIndexCollection indexes = this.listViewDecompositionOrders.SelectedIndices;

            for (int i = indexes.Count - 1; i >= 0; i--)
            {
                listViewDecompositionOrders.Items.RemoveAt(i);
            }
        }

        void inputToolStripMenuItem_Click(object sender, EventArgs e)
        {
            inputDecompositeOrders();
        }

        private void inputDecompositeOrders()
        {
            DialogResult result = new FormInputOrders().ShowDialog();
            

            if (result == DialogResult.OK)
            {
                DecompositionManage DM = new DecompositionManage(this);

               
                DataSet OrderDS;

                if (Logic.SearchDecompositionConditions.GetInstance().Orders.Count>0)
                {

                    OrderDS = DM.GetDecompositionOrders(Logic.SearchDecompositionConditions.GetInstance().Orders);

                        BandListView(OrderDS);

                }
               

               
            }
        }

        void searchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            searchDecompositeOrders();
        }

        private void searchDecompositeOrders()
        {
            DialogResult result = new FormSearchDecompositionConditions().ShowDialog();

            if (result == DialogResult.OK)
            {
                DecompositionManage DM = new DecompositionManage(this);

                DateTimeOffset? starDateTime, finishDateTime;
                DataSet OrderDS;

                if (Logic.SearchDecompositionConditions.GetInstance().IsAllOrders)
                {
                    starDateTime = finishDateTime = null;


                }
                else
                {
                    starDateTime = Logic.SearchDecompositionConditions.GetInstance().StarDateTime;
                    finishDateTime = Logic.SearchDecompositionConditions.GetInstance().FinishDateTime;

                }

                OrderDS = DM.GetDecompositionOrders(starDateTime, finishDateTime);

                BandListView(OrderDS);
            }
        }

        private void inputAllDecompositeOrders()
        {  
            DecompositionManage DM = new DecompositionManage(this);
            DataSet OrderDS = DM.GetDecompositionOrders(null, null);

            BandListView(OrderDS);
        }

        private void BandListView(DataSet ds)
        {
            //begin showmsg
            ParentForm.SetProcessBarBusy();
            ParentForm.SetMsgBar("数据加载中，请稍候...... ");


            if (ds == null)
            {
                ParentForm.IsRun = false;
                return;
            }
            else
            {
                ParentForm.IsRun = true;
            }

            listViewDecompositionOrders.Items.Clear();

            DecompositionDB.DataProvider DP = new Orid.Management.Statistics.Tools.Decomposition.DecompositionDB.DataProvider();

            List<ListViewItem> itemList = null;
            //DataSet Fileld : OrderID,MatterName,OrderDateTime,FinishDateTime
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                ListViewItem item = new ListViewItem();
                Guid orderID = (Guid)row["OrderID"];
                item.Text = orderID.ToString();

                DateTime? lastDecompositeTime = DP.GetLastDecompositeTime( orderID,Util.ServerAddress );
                string lastTime = lastDecompositeTime == null ? "" : lastDecompositeTime.Value.ToString("yyyy-MM-dd HH:mm:ss");

                item.SubItems.AddRange(new string[]{ 
               // row["OrderID"].ToString(),
                row["MatterName"].ToString(),
                row["OrderDateTime"].ToString(),
                row["FinishDateTime"].ToString(),
                lastTime,
                });
                //listViewDecompositionOrders.Items.Add(item);               
                if (itemList == null)
                    itemList = new List<ListViewItem>();

                itemList.Add(item);
            }



            if (itemList != null)
            {
                listViewDecompositionOrders.Items.AddRange(itemList.ToArray()); ;
            }

            ParentForm.SetMsgBar("");
            ParentForm.SetProcessBarNormal();


        }



        private void Star(object sender, EventArgs e)
        {                         

          
            IsAutoRun = true;
            //受番分解
            LoopAllDecomposite();

            if (checkBoxOPRole.Checked)
            {
                //权限分解
                DecompositeOPeratorAndRoles();
            }
            
        }

        public void OnDecompositionFinished()
        {
          

            threadCount--;

            if (threadCount == 0)
            {
                onDecompositionFinished(null);
            }
        }

    

        private void  LoopAllDecomposite()
        {
            List<Guid> listOrder = new List<Guid>(); 
        

            int iCheckedCount = listViewDecompositionOrders.CheckedItems.Count;
        

            foreach (ListViewItem item in listViewDecompositionOrders.CheckedItems)
            {
               
             
                
                    bool isDecomposite = false;
                    string orderID = item.Text;

                    string FinishTime = item.SubItems[3].Text;

                    Guid order = new Guid(orderID);

                  

                    if (FinishTime != string.Empty) 
                    {
                        //上次受番状态已经完成
                        if (!IsOrderFinishedLastTime(order))
                        {
                            isDecomposite = true;

                        }
                        else
                        {
                            if (checkBoxReDecomp.Checked)
                            {
                                isDecomposite = true;
                            }
                        }
                    }
                    else if (FinishTime == string.Empty)
                    {
                        isDecomposite = true;

                    }

                    if (isDecomposite)
                    {

                        listOrder.Add(order);
                 
                    }



            }

//#if  !DEBUG
//            foreach (string item in textBox1.Lines)
//            {
//                listOrder.Add(new Guid (item));
//            }
//#endif

            List<List<Guid>> llistOrder =Logic.SplitList.Split(listOrder, Convert.ToInt32(Config.Setting.SettingInstance.ThreadNumber));

            //manualEvents = new ManualResetEvent[llistOrder.Count];

            threadCount = 0;
            foreach (List<Guid> item in llistOrder)
            {
                threadCount++;

                DecompositionManage DM = new DecompositionManage(this);         
                Thread thread = new Thread(new ParameterizedThreadStart((DM.DecomposeAll)));
                thread.Start(item ); 
   

            }

            
        }


        
        private void Stop(object sender, EventArgs e)
        {
            IsAutoRun = false;
        }

      

        private void SelectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CheckedAll();
        }
        private void CheckedAll()
        {
            foreach (ListViewItem item in listViewDecompositionOrders.Items)
            {
                if (!item.Checked)
                {
                    item.Checked = true;
 
                }

            } 
        }

        private bool IsOrderFinishedLastTime(Guid Orid)
        {
            bool bFlag = false;

            DecompositionDB.DataProvider DP = new Orid.Management.Statistics.Tools.Decomposition.DecompositionDB.DataProvider();

            OrderState state = DP.GetOrderState(Orid);

            if (state == OrderState.Finished)
            {
                bFlag = true;
            }

            return bFlag;
        }

       
    
        public void DecompostiteEnd(Guid orderID )    
        {
       
            GC.Collect();

            int i = 0 ;
            foreach (ListViewItem item in listViewDecompositionOrders.Items)
            {
              
                if (orderID.ToString() == item.Text)
                {
                    item.Tag = "1";
                    item.SubItems[0].BackColor = Color.FromArgb(90, 176, 196, 222);
                  
                }

                if ((item.Tag !=null) && (item.Tag.ToString() == "1") &&  item.Checked)
                {
                    i++;
                }

            }
            
            int iCheckedCount = listViewDecompositionOrders.CheckedItems.Count;

            string msg = "处理状态:" + i.ToString() + "/" + iCheckedCount.ToString();
 
            this.SetMsgBar(msg);

      //      Application.DoEvents();


        }


        private void AutoRun(object sender, EventArgs e)
        {
            normal _normal = new normal(_AutoRun);

            ParentForm.Invoke(_normal);
 
            
        }

        public bool IsAutoRun = false;

        private void _AutoRun()
        {   
           
            ////判断当前是不是在运行程序
            if (IsAutoRun)
            {
                return;
            }
            else
            {
                IsAutoRun = true;
               
            }
            

              //初始化listview
              //填充全部的orders
              inputAllDecompositeOrders();

              //全部选中
              CheckedAll();

 
            ParentForm.IsRun = false;


              //开始
            Star(null, null);
        }

        #region listview 排序

        #region liview排序定义



        private ListViewColumnSorter lvwColumnSorter;
        class ListViewColumnSorter : IComparer
        {
            /// <summary>
            /// 指定按照哪个列排序
            /// </summary>
            private int ColumnToSort;
            /// <summary>
            /// 指定排序的方式
            /// </summary>
            private System.Windows.Forms.SortOrder OrderOfSort;
            /// <summary>
            /// 声明CaseInsensitiveComparer类对象，
            /// 参见ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/cpref/html/frlrfSystemCollectionsCaseInsensitiveComparerClassTopic.htm
            /// </summary>
            private CaseInsensitiveComparer ObjectCompare;
            /// <summary>
            /// 构造函数
            /// </summary>
            public ListViewColumnSorter()
            {
                // 默认按第一列排序
                ColumnToSort = 0;
                // 排序方式为不排序
                OrderOfSort = System.Windows.Forms.SortOrder.None;
                // 初始化CaseInsensitiveComparer类对象
                ObjectCompare = new CaseInsensitiveComparer();
            }
            /// <summary>
            /// 重写IComparer接口.
            /// </summary>
            /// <param name="x">要比较的第一个对象</param>
            /// <param name="y">要比较的第二个对象</param>
            /// <returns>比较的结果.如果相等返回0，如果x大于y返回1，如果x小于y返回-1</returns>
            public int Compare(object x, object y)
            {
                int compareResult;
                //当点击Remaining Job Count列的时候 不是用item的text排序 是用MaxJobCount来排序
              
                
                    ListViewItem listviewX, listviewY;

                    // 将比较对象转换为ListViewItem对象
                    listviewX = (ListViewItem)x;
                    listviewY = (ListViewItem)y;

                    // 比较
                    compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
                 
                // 根据上面的比较结果返回正确的比较结果
                    if (OrderOfSort == System.Windows.Forms.SortOrder.Ascending)
                {
                    // 因为是正序排序，所以直接返回结果
                    return compareResult;
                }
                else if (OrderOfSort ==System.Windows.Forms. SortOrder.Descending)
                {
                    // 如果是反序排序，所以要取负值再返回
                    return (-compareResult);
                }
                else
                {
                    // 如果相等返回0
                    return 0;
                }
            }
            /// <summary>
            /// 获取或设置按照哪一列排序.
            /// </summary>
            public int SortColumn
            {
                set
                {
                    ColumnToSort = value;
                }
                get
                {
                    return ColumnToSort;
                }
            }
            /// <summary>
            /// 获取或设置排序方式.
            /// </summary>
            public System.Windows.Forms.SortOrder Order
            {
                set
                {
                    OrderOfSort = value;
                }
                get
                {
                    return OrderOfSort;
                }
            }
        }
        #endregion liview排序定义

        private void FormManageDecompositionOrders_Load(object sender, EventArgs e)
        {
            lvwColumnSorter = new ListViewColumnSorter();
            this.listViewDecompositionOrders.ListViewItemSorter = lvwColumnSorter;
            listViewDecompositionOrders.ColumnClick += new ColumnClickEventHandler        (listViewDecompositionOrders_ColumnClick);
        }

        void listViewDecompositionOrders_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                if (lvwColumnSorter.Order == System.Windows.Forms.SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Ascending;
                }
            }
            else
            {
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Ascending;
            }
            this.listViewDecompositionOrders.Sort();
        }


        #endregion


        private void SetMsgBar(string msg)
        {
            ParentForm.SetMsgBar( msg);
        }

        /// <summary>
        /// 权限分解
        /// </summary>
        private void DecompositeOPeratorAndRoles()
        {
            IsAutoRun = true;
            threadCount++;

            DecompositionManage DM = new DecompositionManage(this);

            Thread thread = new Thread(new ThreadStart(DM.DecomposeRolePerson));
            thread.Start();
        }
    }
}
